package objects;
import materials.Material;
import math.Vector3D;
import render.Ray;
import render.TraceResult;

public class Sphere extends RenderObject {

    private double radius;

    public Sphere( Vector3D position , Material material , double radius) {
	super( position, material);
	this.setRadius( radius );
    }

    public void setRadius( double radius ) {
	this.radius = radius;
    }

    public double getRadius() {
	return radius;
    }

    public TraceResult trace( Ray ray ) {
	
	if(Vector3D.distance(ray.getPosition(),position) <= radius)
	    return new TraceResult( false , 0 );
	
	Vector3D rayToSphereCenter = position.minus( ray.getPosition() );

	double lengthRTSC2 = rayToSphereCenter.dot( rayToSphereCenter );
	double closestApproach = rayToSphereCenter.dot( ray.getDirection() );
	if ( closestApproach < 0 ) {
	    return new TraceResult( false , 0 );
	}

	double halfCord2 = (radius * radius) - lengthRTSC2 + (closestApproach * closestApproach);

	if ( halfCord2 < 0 ) 
	{
	    return new TraceResult( false , 0 );
	}

	return new TraceResult( true , closestApproach - Math.sqrt( halfCord2 ) );

    }

    public Vector3D getNormal(Vector3D intersect){
    return intersect.minus(position).div( radius);
    }
}
